<?php

namespace App\Helper\Utils;

use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Intervention\Image\ImageManagerStatic;

/**
 * Class Util
 * @package App\Helper\Utils
 */
class Util
{
    /**
     * 验证手机号是否合法
     * @param string $phone 手机号
     * @param string $country 国家
     * @return bool
     */
    public static function checkPhone($phone)
    {
        $phone = static::formatContactPhone($phone);
        $pattern = '/^[0-9]{10,12}$/';
        if (preg_match($pattern, $phone)) {
            return true;
        } else {
            return false;
        }

    }
    /**
     * 格式化联系人手机
     *
     * @param string $phone
     * @param string $country 国家
     *
     * @return string
     */
    public static function formatContactPhone($phone)
    {
        $phone = trim($phone);
        if (strpos($phone, '+52') === 0) {
            $phone = substr($phone, 3);
        }
        //去除手机号中非数字的字符dd
        preg_match_all('/\d+/', $phone, $phoneArr);
        $phone = join('', $phoneArr[0]);
        //52，也写作0052、+52，其他可能出现的显示有：00 52、00-52、+52-、+0052、052、00052
        //去除手机号中非数字字符串
        $phone = trim($phone);
        if (strpos($phone, '0052') === 0) {
            $phone = substr($phone, 4);
        }
        // 如果号码长度是12位，则直接去除 开头的 52
        if (strpos($phone, '52') === 0 && strlen($phone) === 12) {
            $phone = substr($phone, 2);
        }
        // 如果号码长度是13位，则直接去除 开头的 521
        if (strpos($phone, '521') === 0 && strlen($phone) === 13) {
            $phone = substr($phone, 3);
        }
        if (strpos($phone, '0') === 0 && strlen($phone) === 11) {
            $phone = substr($phone, 1);
        }
        return $phone;
    }

    /**
     * 邮箱校验
     * @param $email
     * @return bool
     */
    public static function checkEmail($email)
    {
        $regex= '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
        if (preg_match($regex,$email)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 产生一个随机字符串
     * @param int $length
     * @return string
     */
    public static function randStr($length) {
        $codeRand = "0123456789asdfghjklmyuiopqwertnbvcxzASDFGHJKLMYUIOPQWERTNBVCXZ";
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $key = rand(0, 61);
            $string .=$codeRand[$key];
        }
        return $string;
    }

    /**
     * 将时间戳转换成星期格式 (东八区)
     * @param $timestamp
     * @return int 0 周日 1 周一 2 周二 3 周三 4 周四 5 周五 6 周六
     */
    public static function getWeekly($timestamp)
    {
        $days = intval(($timestamp+8*60*60)/(24*60*60));
        $mod = ($days+4) % 7;
        return $mod;
    }

    /**
     * 判断是否是工作日
     * @param $timestamp
     * @return bool
     */
    public static function isWeekday($timestamp)
    {
        $weekday = self::getWeekly($timestamp);
        if($weekday == 0 || $weekday == 6) {
            return false;
        }
        return true;
    }

    /**
     * 验证身份证是否合法
     * @param $id_number
     * @return bool
     */
    public static function checkIdNumber($id_number)
    {

        $pattern = '/^\d{17}[\d\w]$|^\d{15}$/';
        if (preg_match($pattern, $id_number)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 计算两点地理坐标之间的距离
     * @param float $longitude1 起点经度
     * @param float $latitude1 起点纬度
     * @param float $longitude2 终点经度
     * @param float $latitude2 终点纬度
     * @param integer $unit 单位 1:米 2:公里
     * @param integer $decimal 精度 保留小数位数
     * @return float
     */
    public static function getDistance(float $longitude1, float $latitude1, float $longitude2, float $latitude2, $unit = 1, $decimal = 2): float
    {

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI / 180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if ($unit == 2) {
            $distance = $distance / 1000;
        }
        return round($distance, $decimal);
    }
    /**
     * 获取当前的IP
     * @return string
     */
    public static function getIp()
    {
        $onlineip = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        return $onlineip;
    }

    static public function uploadFile($request, $mainId)
    {
        $files = $request->file('images');

        if(!in_array($files->extension(), ['jpg', 'jpeg', 'png'])) {
            return ['code' => '1', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`', 'data' => ''];
        }

        $name= SELF::randStr(rand(9, 20)).'.'.$files->extension();//随机生成的字符串,可以自行拼接图片名字
        $path = 'uploads/'.date('Y').'/'.date('m').'/'.date('d').'/';
        $fullPath = $path.$name;
        if(!file_exists($path)) {
            mkdir($path, 0777, true);
        }

        $img = ImageManagerStatic::make($files)
            ->resize(null,120, function($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            })
            ->orientate();//压缩并保存照片

        $result = saveFileSize(['main_id' => $mainId], $img->filesize(), '/'.$fullPath);

        if($result['code']) {
            return $result['msg'];
        }

        return '/'.$fullPath;
    }

    /**
     * 上传图片
     * @author sunwu
     * @return string
     */
    static public function uploadFile1($request, $mainId)
    {
        $files = $request->file('images');
        //图片大小
        $fileSize = $files->getSize();
        $ext = $files->extension();

        if(!in_array($ext, ['jpg', 'jpeg', 'png'])) {
            return ['code' => '1', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`', 'data' => ''];
        }

        $path = $files->store(date('Y').'/'.date('m').'/'.date('d'));

        $result = saveFileSize(['main_id' => $mainId], $fileSize, ['/uploads/'.$path]);
        if($result['code'] != 0) {
            return $result;
        }

        return ['code' => 0, 'msg' => 'success', 'data' => '/uploads/'.$path];
    }
}
